import './assets/main.css';
import { createApp } from 'vue';
import { createPinia } from 'pinia';
import { renderWithQiankun, qiankunWindow } from 'vite-plugin-qiankun/dist/helper';
import App from './App.vue';
import Antd from 'ant-design-vue';
import 'ant-design-vue/dist/reset.css';
import getRouter from './router';
import * as Icons from '@ant-design/icons-vue';

let app = null;

if (!qiankunWindow.__POWERED_BY_QIANKUN__) {
  app = createApp(App);
  // 全局引入antd icon
  Object.keys(Icons).forEach(key => {
    app.component(key, Icons[key]);
  });
  app.use(Antd).use(createPinia()).use(getRouter()).mount('#app');
} else {
  // 配置微应用。给qiankun定义生命周期
  const container = document.getElementById('app');
  if (container) {
    renderWithQiankun({
      mount(props) {
        app = createApp(App);
        // 全局引入antd icon
        Object.keys(Icons).forEach(key => {
          app.component(key, Icons[key]);
        });
        app
          .use(Antd)
          .use(createPinia())
          .use(getRouter(props.routerBase))
          .mount(props.container ? props.container.querySelector('#app') : document.getElementById('app'));
        // 监听主应用注入的全局状态
        props.onGlobalStateChange((state, prev) => {
          // state: 变更后的状态; prev 变更前的状态
          console.log({ state, prev });
        });
      },
      bootstrap() {
        console.log('--bootstrap');
      },
      update(props) {
        console.log('--update', props);
      },
      unmount() {
        console.log(app, '======unmount');
        app?.unmount();
      },
    });
  } else {
    console.log('not exist');
  }
}
